//
//  SoundDiagnosisService.m
//  MobileChecker
//
//  Created by Lymons on 15-1-12.
//  Copyright (c) 2015年 Lymons. All rights reserved.
//

#import "SoundDiagnosisService.h"
#import <MediaPlayer/MediaPlayer.h>

static float originalVolumn = -1;

typedef enum {
    PlayMediumHeaphone = 2,
    PlayMediumSpeaker = 1
} PlayMedium;

@interface UIAlertView (Cancel)

- (void)dismiss;

@end

@implementation UIAlertView (Cancel)

- (void)dismiss
{
    if (self.isVisible) {
        [self dismissWithClickedButtonIndex:0 animated:NO];
    }
}

@end

@interface SoundDiagnosisService ()
{
    SoundDiagnosisServiceType serviceType;
}

@property (nonatomic, strong) NSURL *recordedFile;
@property (nonatomic, strong) AVAudioPlayer *player;
@property (nonatomic, weak) id<RACSubscriber> subscriber;
@property (nonatomic, assign) PlayMedium playMedium;
@property (nonatomic, strong) RACSignal *signalEnd;
@property (nonatomic, strong) RACSignal *signalToast;
@property (nonatomic, strong) UIAlertView *alertView;

@end

@implementation SoundDiagnosisService

- (id)initWithSoundDiagnosisServiceType:(SoundDiagnosisServiceType)type
{
    self = [super init];
    if (self) {
        serviceType = type;
        [self resetPlayMedium];
        
        
    }
    return self;
}

- (RACSignal *)signalEnd
{
    if (_signalEnd == nil) {
        _signalEnd = [self rac_signalForSelector:@selector(endCheckOnTimer:)];
    }
    return _signalEnd;
}

- (RACSignal *)signalToast
{
    if (_signalToast == nil) {
        _signalToast = [self rac_signalForSelector:@selector(play)];
        [self subscribeSignalToast];
    }
    return _signalToast;
}

- (void)subscribeSignalToast
{
    if ([[[UIDevice currentDevice] model] isEqualToString:@"iPhone"]) {
        @weakify(self);
        [self.signalToast subscribeNext:^(id x) {
            @strongify(self);
            if (self.playMedium == PlayMediumHeaphone) {
                self.toastMessage = @"受話器から音を再生しています。\n耳を受話器に近付けてください。";
            } else {
                self.toastMessage = @"スピーカーから音を再生しています。";
            }
            if (self->serviceType == SoundDiagnosisServiceTypeMedia) {
                [self showAlertWithString:self.toastMessage];
            }
        }];
    }
}

- (void)startCheck:(id<RACSubscriber>)subscriber
{
    self.subscriber = subscriber;
    [self signalToast];
    
    [self.signalEnd subscribeNext:^(id x) {
        [subscriber sendNext:@(YES)];
        [subscriber sendCompleted];
    }];

    @weakify(self);
    void (^playBlock)() = ^() {
        @strongify(self);
        NSError *playerError;
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.recordedFile error:&playerError];
        
        if (playerError) {
            NSLog(@"ERror creating player: %@", [playerError description]);
            [self endCheckOnTimer:nil];
            return;
            
        }
        
        MPMusicPlayerController *mpc = [MPMusicPlayerController applicationMusicPlayer];
        
        if (originalVolumn < 0) {
            originalVolumn = mpc.volume;
        }
        mpc.volume = 1.0;  //0.0~1.0
         
        self.player.delegate = self;
        [self play];
    };
    
    switch (serviceType) {
        case SoundDiagnosisServiceTypeRecord:
            
            if (![self prepareToPlayRecord]) {
                return;
            }
            playBlock();
            break;
            
        case SoundDiagnosisServiceTypeMedia:
            
            if (![self prepareToPlayMedia]) {
                return;
            }
            playBlock();
            break;
            
        default:
            break;
    }
}

- (void)endCheckOnTimer:(id<RACSubscriber>)subscriber
{
    self.toastMessage = nil;
    if ([self.player isPlaying]) {
        [self.player stop];
    }
    
    if (originalVolumn >= 0) {
        MPMusicPlayerController *mpc = [MPMusicPlayerController applicationMusicPlayer];
        mpc.volume = originalVolumn;  //0.0~1.0
        originalVolumn = -1;
    }
}

#pragma mark - play
- (void)play {
    if (self.playMedium == PlayMediumHeaphone) {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    } else {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    }
    
    [self.player play];
//    self.isSwithing = NO;
//    [self performSelector:@selector(endingSwitch) withObject:nil afterDelay:2];
}

- (BOOL)prepareToPlayMedia
{
    if (self.recordedFile == nil) {
        if ([self audioSession] == nil) {
            return NO;
        }
        
        NSString *fileName = [[NSBundle mainBundle] pathForResource:@"record_diagnosis" ofType:@"mp3"];
        self.recordedFile = [NSURL fileURLWithPath:fileName];
    }
    
    return YES;
}

- (BOOL)prepareToPlayRecord
{
    if (self.recordedFile == nil) {
        if ([self audioSession] == nil) {
            return NO;
        }
        
        NSString *fileName = kRecodeFileName;
        self.recordedFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:fileName]];
    }
    
    return YES;
}

- (AVAudioSession *)audioSession
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    BOOL audioAvailable = audioSession.inputAvailable;
    if (audioAvailable == NO) {
        return nil;
    }
    
    NSError *sessionError;
    [audioSession setCategory:AVAudioSessionCategorySoloAmbient error:&sessionError];
    
    if(audioSession == nil) {
        NSLog(@"Error creating session: %@", [sessionError description]);
    } else {
        [audioSession setActive:YES error:nil];
    }
    
    return audioSession;
}

#pragma mark - AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self.alertView dismiss];
    self.toastMessage = nil;
    self.playMedium--;
    if (self.playMedium > 0) {
        [self play];
    } else {
        [self endCheckOnTimer:nil];
        [self resetPlayMedium];
    }
}

#pragma mark - utils
- (void)resetPlayMedium
{
    if ([[[UIDevice currentDevice] model] isEqualToString:@"iPhone"]) {
        self.playMedium = PlayMediumHeaphone;
    } else {
        self.playMedium = PlayMediumSpeaker;
    }
}

- (void)showAlertWithString:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@" "
                                                    message:message
                                                   delegate:self
                                          cancelButtonTitle:@"停止"
                                          otherButtonTitles:nil];
    //    [[alert rac_buttonClickedSignal] subscribeNext:^(id x) {
    //        NSLog(@"%@",x);
    //    }];
    self.alertView = alert;
    [alert show];
    [self.alertView performSelector:@selector(dismiss) withObject:nil afterDelay:self.player.duration-3];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"%@", @"stop");
    if ([self.player isPlaying] && self.playMedium > 0) {
        [self.player stop];
        [self audioPlayerDidFinishPlaying:self.player successfully:NO];
    }
}

@end
